 <template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="pd.showSearch">
        <el-form :model="pd.queryParams" ref="queryFormRef" :inline="true" label-width="68px">
          <el-form-item label="任务名称" prop="taskName">
            <el-input v-model="pd.queryParams.taskName" placeholder="请输入任务名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="计划单号" prop="scheduleLineId">
            <el-input v-model="pd.queryParams.scheduleLineId" placeholder="请输入计划单号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="物品名称" prop="productId">
            <ProductSearch :data-text="pd.queryParams.productName" @ok="searchProduct" :params="{isStock:true}"/>
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select v-model="pd.queryParams.status" placeholder="请选择状态" clearable>
              <el-option v-for="dict in wms_task_status" :key="dict.value" :label="dict.name" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="生产线" prop="workshopLineId">
            <el-select v-model="pd.queryParams.workshopLineId" placeholder="请选择生产线" clearable>
              <el-option v-for="item in pd.workShopLine" :key="item.id" :label="item.name" :value="item.id" />
            </el-select>
          </el-form-item>
          <el-form-item label="批次号" prop="batchCode">
            <el-input v-model="pd.queryParams.batchCode" placeholder="请输入批次号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="开始生产时间" prop="startTime">
            <el-date-picker clearable
              v-model="pd.queryParams.startTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择开始生产时间"
            />
          </el-form-item>
          <el-form-item label="完成生产时间" prop="endTime">
            <el-date-picker clearable
              v-model="pd.queryParams.endTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="请选择完成生产时间"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="pd.single[0]" @click="nextStatus({},'1')" v-hasPermi="['wms:task:edit']">派工</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Edit" :disabled="pd.single[1]" @click="nextStatus({},'2')" v-hasPermi="['wms:task:edit']">上线</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Edit" :disabled="pd.single[2]" @click="nextStatus({},'3')" v-hasPermi="['wms:task:edit']">返工</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="info" plain icon="Edit" :disabled="pd.single[3]" @click="nextStatus({},'4')" v-hasPermi="['wms:task:edit']">完工</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Edit" :disabled="pd.single[4]" @click="nextStatus({},'5')" v-hasPermi="['wms:task:edit']">报工</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['wms:task:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="pd.showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table ref="refTable" v-loading="pd.loading" :data="pd.taskList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="任务id" align="center" prop="id" v-if="true" />
        <el-table-column label="任务名称" align="center" prop="taskName" />
        <el-table-column label="计划单号" align="center" prop="scheduleLineId" />
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="物品名称" align="center" prop="productName" />
        <el-table-column label="批次号" align="center" prop="batchCode" />
        <el-table-column label="生产数量" align="center" prop="quantity" />
        <el-table-column label="开始生产时间" align="center" prop="startTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="完成生产时间" align="center" prop="endTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="wms_task_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column fixed="left" label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button v-show="scope.row.status === '0'" link type="primary" icon="Check" @click="nextStatus(scope.row,'1')" v-hasPermi="['wms:task:edit']">派工</el-button>
            <el-button v-show="scope.row.status === '1'" link type="primary" icon="Check" @click="nextStatus(scope.row,'2')" v-hasPermi="['wms:task:edit']">上线</el-button>
            <el-button v-show="scope.row.status === '2'" link type="primary" icon="Check" @click="nextStatus(scope.row,'3')" v-hasPermi="['wms:task:edit']">返工</el-button>
            <el-button v-show="scope.row.status === '2' || scope.row.status === '3'" link type="primary" icon="Check" @click="nextStatus(scope.row,'4')" v-hasPermi="['wms:task:edit']">完工</el-button>
            <el-button v-show="scope.row.status === '4'" link type="primary" icon="Check" @click="nextStatus(scope.row,'5')" v-hasPermi="['']">入库</el-button>
            <el-tag v-show="scope.row.status === '5'" icon="finish">结束</el-tag>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="pd.total>0" :total="pd.total" v-model:page="pd.queryParams.pageNum"
                  v-model:limit="pd.queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改生产工单对话框 -->
    <el-dialog :title="pd.dialog.title" v-model="pd.dialog.visible" width="500px" append-to-body>
      <el-form ref="taskFormRef" :model="pd.form" :rules="pd.rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="pd.form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="计划单号" prop="scheduleLineId">
          <el-input v-model="pd.form.scheduleLineId" placeholder="请输入计划单号" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="pd.form.sort" placeholder="请输入排序" />
        </el-form-item>
        <el-form-item label="物品id" prop="productId">
          <el-input v-model="pd.form.productId" placeholder="请输入物品id" />
        </el-form-item>
        <el-form-item label="批次号" prop="batchCode">
          <el-input v-model="pd.form.batchCode" placeholder="请输入批次号" />
        </el-form-item>
        <el-form-item label="开始生产时间" prop="startTime">
          <el-date-picker clearable
            v-model="pd.form.startTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始生产时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="完成生产时间" prop="endTime">
          <el-date-picker clearable
            v-model="pd.form.endTime"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择完成生产时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="pd.buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Task" lang="ts">
import {TaskVO, listTask, getTask, delTask, addTask, updateTask } from '@/views/wms/task/api';
import ProductSearch from '@/views/wms/product/search.vue'
import {ProductVO} from "@/views/wms/product/api";
import {listWorkshop} from "@/views/wms/workshopLine/api";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { wms_task_status } = toRefs<any>(proxy?.useDict('wms_task_status'));


const queryFormRef = ref<ElFormInstance>();
const taskFormRef = ref<ElFormInstance>();

const pd = reactive({
  taskList: <TaskVO[]>([]),
  buttonLoading: false,
  loading: true,
  showSearch: true,
  selectVO: <TaskVO[]>([]),
  workShopLine: [] as any,
  single: <boolean[]>([true,true,true,true,true]),
  multiple: true,
  total: 0,
  form: <TaskVO>{},
  queryParams: <TaskVO>{
    pageNum: 1,
    pageSize: 10,
    taskName: undefined,
    scheduleLineId: undefined,
    productId: undefined,
    batchCode: undefined,
    startTime: undefined,
    endTime: undefined,
    status: undefined,
    params: {
    }
  },
  rules: <ElFormRules>{
    id: [
      { required: true, message: "任务id不能为空", trigger: "blur" }
    ],
    taskName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    scheduleLineId: [
      { required: true, message: "计划单号不能为空", trigger: "blur" }
    ],
    sort: [
      { required: true, message: "排序不能为空", trigger: "blur" }
    ],
    productId: [
      { required: true, message: "物品id不能为空", trigger: "blur" }
    ],
    batchCode: [
      { required: true, message: "批次号不能为空", trigger: "blur" }
    ],
    startTime: [
      { required: true, message: "开始生产时间不能为空", trigger: "blur" }
    ],
    endTime: [
      { required: true, message: "完成生产时间不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "任务状态不能为空", trigger: "change" }
    ],
  },
  dialog: <DialogOption>{
    visible: false,
    title: ''
  }
});

/** 查询生产工单列表 */
async function getList() {
  pd.loading = true;
  await listTask(pd.queryParams).then((res)=>{
    pd.taskList = res.rows;
    pd.total = res.total;
    pd.loading = false;
  });
}

/** 取消按钮 */
function cancel() {
  reset();
  pd.dialog.visible = false;
}

/** 表单重置 */
function reset() {
  pd.form = {};
  taskFormRef.value?.resetFields();
}

/** 搜索按钮操作 */
function handleQuery() {
  pd.queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryFormRef.value?.resetFields();
  pd.queryParams.productName = '';
  handleQuery();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: TaskVO[]) {
  if (selection.length === 0) {
    pd.single[0] = true;
    pd.single[1] = true;
    pd.single[2] = true;
    pd.single[3] = true;
    pd.single[4] = true;
    return
  }
  pd.selectVO = selection;
  let uniqueStatus = '';
  if (pd.selectVO.length > 1){
    if (pd.selectVO.every(item => item.status == pd.selectVO[0].status)){
      uniqueStatus = pd.selectVO[0].status!;
    }
  }else{
    uniqueStatus = pd.selectVO[0].status!;
  }

  pd.single[0] = uniqueStatus !== "0";
  pd.single[1] = uniqueStatus !== "1";
  pd.single[2] = uniqueStatus !== "2";
  pd.single[3] = uniqueStatus !== "3" && uniqueStatus !== "2";
  pd.single[4] = uniqueStatus !== "4";

  pd.multiple = !selection.length;
}

/** 提交按钮 */
function submitForm() {
  taskFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      pd.buttonLoading = true;
      if (pd.form.id) {
        await updateTask(pd.form).finally(() =>  pd.buttonLoading = false);
      } else {
        await addTask(pd.form).finally(() =>  pd.buttonLoading = false);
      }
      proxy?.$modal.msgSuccess("修改成功");
      pd.dialog.visible = false;
      await getList();
    }
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy?.download('wms/task/export', {
    ...pd.queryParams
  }, `task_${new Date().getTime()}.xlsx`)
}

async function nextStatus(row: TaskVO,status: string){
  const _ids = row.id || pd.selectVO.map(v => v.id);
  await proxy?.$modal.confirm('是否确认操作生产工单编号为"' + _ids + '"的数据项？').finally(() => pd.loading = false);
  if (row.id){
    let vo = row;
    vo.status = status;
    await updateTask(vo).then(()=>{proxy?.$modal.msgSuccess("操作成功")}).finally(() => {
      pd.buttonLoading = false;
      getList();
    });
  }else{
    for (const data of pd.selectVO){
      let vo = data;
      vo.status = status;
      await updateTask(vo).then(()=>{proxy?.$modal.msgSuccess("操作成功")}).finally(() => {
        pd.buttonLoading = false;
        getList();
      });
    }
  }
  (proxy?.$refs["refTable"] as any).clearSelection();
  pd.selectVO = []
}

/** 生产流水线 */
async function workShopLine() {
  const res = await listWorkshop();
  pd.workShopLine = res.rows;
}

function searchProduct(value: ProductVO[]) {
  pd.queryParams.productId = value[0].id as number;
  pd.queryParams.productName = value[0].name;
}

onMounted(() => {
  getList();
  workShopLine()
});
</script>
